package com.taocyb.web.uc;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taocyb.bean.uc.LoginBean;
import com.taocyb.commons.uc.entity.User;
import com.taocyb.commons.uc.entity.UserIpLog;
import com.taocyb.commons.uc.service.UserLogService;
import com.taocyb.commons.uc.service.UserService;
import com.taocyb.constant.UrlEnum;
import com.taocyb.constant.uc.UserStatus;
import com.taocyb.framework.remote.http.HttpClientUtils;
import com.taocyb.framework.utils.JsonMapper;
import com.taocyb.framework.utils.SecurityUtils;
import com.taocyb.framework.utils.Servlets;
import com.taocyb.web.BaseController;

/**
 * 用户中心
 */
@Controller
@RequestMapping(value = "/uc/security")
public class SecurityController extends BaseController{
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserLogService userLogService;
	
	@RequestMapping(value = "/login", method=RequestMethod.GET)
	public String index(){
		return "uc/security-login";
	}
	
	/**
	 * ajax登录
	 */
	@RequestMapping(value = "/login", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> login(HttpServletRequest request, HttpServletResponse response, LoginBean bean){
		User user = userService.findUserByLoginName(bean.getLoginName());
		Map<String, Object> map = new HashMap<String, Object>();
		if(null == user){	//账号不存在
			map.put("status", 0);
			map.put("message", "账号或者密码错误");
		}else if(!user.getPassword().equals(SecurityUtils.sha1Password(bean.getPassword(), user.getSalt()))){	//账号或者密码错误	
			map.put("status", 0);
			map.put("message", "账号或者密码错误");
		}else if(UserStatus.FREEZE.key == user.getStatus()){	//账号存在异常
			map.put("status", 2);
			map.put("message", "该账号已被冻结");
		}else{	//登陆成功
			map.put("status", 1);
			map.put("message", "登陆成功!");
			this.writeCookie(response, user);
			this.saveIpLog(request, user);
		}
		
		return map;
	}
	
	/**
	 * ajax注销
	 */
	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response){
		Cookie cookie = Servlets.getCookie(request, "_uid");
		if(null != cookie){
			cookie.setMaxAge(0);
			cookie.setPath("/");
			response.addCookie(cookie);
		}
		
		return null;
	}
	
	/**
	 * 登录信息写入cookie
	 * http://blog.csdn.net/jpr1990/article/details/6708534
	 */
	private void writeCookie(HttpServletResponse response, User user){
		int expiry = 60 * 30;	//30分钟有效时长
		
		String cookieValue = SecurityUtils.encryptCookieValueBase64(user.getLoginName(), user.getPassword(), expiry);
		
		Cookie cookie = new Cookie("_uid", cookieValue);
		cookie.setPath("/");
		cookie.setMaxAge(expiry);	//浏览器关闭失效
		response.addCookie(cookie);
	}	
	
	/**
	 * 保存登录IP日志 
	 */
	@SuppressWarnings("unchecked")
	private void saveIpLog(HttpServletRequest request, User user){
		String ip = Servlets.getRemoteIp(request);
		String jsonString = HttpClientUtils.doGet(UrlEnum.IP.value + "?ip=" + ip);
		Map<String, String> map = JsonMapper.nonEmptyMapper().fromJson(jsonString, Map.class);
		
		UserIpLog ipLog = new UserIpLog();
		ipLog.setUserId(user.getId());
		ipLog.setLoginName(user.getLoginName());
		ipLog.setCountry(map.get("country"));
		ipLog.setProvince(map.get("area"));
		ipLog.setCity(map.get("city"));
		ipLog.setCounty(map.get("county"));
		ipLog.setIsp(map.get("isp"));
		ipLog.setIp(ip);
		
		userLogService.saveUserIpLog(ipLog);
	}
}
